package com.vancouver.knows;

import java.util.HashMap;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.facebook.FacebookSdk;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.pangu.AMApplication;
import com.pangu.bean.DeviceConfig;
import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.bean.SplashAdInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.bean.VersionInfo;
import com.vancouver.knows.business.task.mark.AddUserTokenTaskMark;
import com.vancouver.knows.business.task.mark.SplashAdInfoTaskMark;
import com.vancouver.knows.business.task.mark.UserGetAuidTaskMark;
import com.vancouver.knows.business.task.mark.UserHashTaskMark;
import com.vancouver.knows.business.task.mark.VersionInfoTaskMark;
import com.vancouver.knows.event.SystemEvent;
import com.vancouver.knows.event.SystemEventConst;
import com.vancouver.knows.gcm.CommonUtilities;
import com.vancouver.knows.manager.PhoBeanManager;
import com.vancouver.knows.manager.PhoSharedPrefManager;
import com.vancouver.knows.service.RegistrationInstanceIdService;
import com.vancouver.knows.ui.activity.TutorialActivity;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.activity.version.UpdateDialog;
import com.vancouver.knows.util.AfTrackerUtil;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.PhoConstants;

/**
 * 应用全局 Created by chenxunlin_91 on 2015/8/24.
 */
public class MainApplication extends AMApplication<PhoBeanManager, PhoSharedPrefManager, PhoContextConfig> {
	private BSharedPrefManager sharedPrefManager;

	private static final String PROPERTY_ID = "UA-68960259-3";//"UA-73793356-3";// UA-73793356-1,UA-68960259-3
	public double latitude = 0;
	public double longitude = 0;

	public enum TrackerName {
		APP_TRACKER, GLOBAL_TRACKER, ECOMMERCE_TRACKER,
	}

	public HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

	@Override
	protected PhoBeanManager createBeanManager() {
		return new PhoBeanManager(this);
	}

	@Override
	public PhoSharedPrefManager getSharedPrefManager() {
		return mBeanManager.getSharedPrefManager();
	}

	@Override
	public PhoContextConfig getContextConfig() {

		return mBeanManager.getContextConfig();
	}

	@Override
	protected void onRemoteProcessInit(String processName) throws Exception {

	}

	@Override
	protected void preInitApplication() {
		super.preInitApplication();
		FacebookSdk.sdkInitialize(getApplicationContext());

	}

	@Override
	protected void initContextConfig() throws Exception {
	}

	@Override
	protected void initPreDataLoad() {
		super.initPreDataLoad();
		initUserInfo();
		showSplashAd();
		sendUpdateVersion();
		initFirebase();
		//initGcm();
	}

	/**
	 * 用户首次安装app时无需显示开屏广告，之后则每次用户打开app时都访问接口看有没有广告
	 */
	private void showSplashAd() {
		if (sharedPrefManager != null) {
			//true 说明首次已经登录过
			if (sharedPrefManager.getFirstLoginSign()) {
				Intent tutorialIntent = new Intent(getApplicationContext(), TutorialActivity.class);
				tutorialIntent.putExtra(TutorialActivity.TUTORIAL_EXTRA, BSharedPrefManager.WALKTHOUGH_SPLASH_AD);
				startActivity(tutorialIntent);

				//发送请求splash Ad 广告接口
				Message msg = Message.obtain();
				msg.what = Constants.BUSINESS_STATUS_SPLASH_AD;
				this.handleMobMessage(msg);
			}
		}
	}

	private void initFirebase() {
		initTopic();
		initFcmToken();
	}

	private void initTopic() {
		if (CommonUtilities.checkPlayServices(this)) {
			FirebaseMessaging.getInstance().subscribeToTopic("broadcast-android");
			//FirebaseMessaging.getInstance().subscribeToTopic("broadcast_android");
		}
	}

	private void initFcmToken() {
		String token = FirebaseInstanceId.getInstance().getToken();
		if (token != null && CommonUtilities.checkPlayServices(this) ) {
			Intent intent = new Intent(this, RegistrationInstanceIdService.class);
			startService(intent);
			Log.i(TAG, "Token11: " + token);
		}
	}

	private void initUserInfo() {
		UserInfo userInfo = null;
		sharedPrefManager = new BSharedPrefManager(this);
		if (!StringUtil.isEmptyString(sharedPrefManager.getUserId())) {
			userInfo = new UserInfo();
			userInfo.setUserID(sharedPrefManager.getUserId());
			userInfo.setName(sharedPrefManager.getUserName());
			userInfo.setEmail(sharedPrefManager.getUserEmail());
			userInfo.setAvatar(sharedPrefManager.getAvatar());
			userInfo.setLogin(sharedPrefManager.getLogin());
			userInfo.setTotalUnReadComment(sharedPrefManager.getTotalUnReadComment());
			userInfo.setTotalUnReadPostComment(sharedPrefManager.getTotalUnReadPostComment());
			//积分明细
			userInfo.userPointsDetailsInfo.setTotalPoints(sharedPrefManager.getTotalPoints());
			userInfo.userPointsDetailsInfo.setPostPoints(sharedPrefManager.getPostPoints());
			userInfo.userPointsDetailsInfo.setUpvotePoints(sharedPrefManager.getUpvotePoints());
			userInfo.userPointsDetailsInfo.setCommentPoints(sharedPrefManager.getCommentPoints());
			userInfo.userPointsDetailsInfo.setPostUpvotePoints(sharedPrefManager.getPostUpvotePoints());
			userInfo.userPointsDetailsInfo.setCommentUpvotePoints(sharedPrefManager.getCommentUpvotePoints());
			userInfo.userPointsDetailsInfo.setRedeemedPoints(sharedPrefManager.getRedeemedPoints());
			userInfo.userPointsDetailsInfo.setPointsPolicy(sharedPrefManager.getPointsPolicy());
			userInfo.userPointsDetailsInfo.setPointsStore(sharedPrefManager.getPointsStore());
			userInfo.userPointsDetailsInfo.setImageSharePoints(sharedPrefManager.getImagePoints());
		}
		getBusinessModule().getCacheManager().setUserInfo(userInfo);
	}

	public void initGcm() {
//		try {
//			if (CommonUtilities.checkPlayServices(this)) {
//				Intent intent = new Intent(this, RegistrationInstanceIdService.class);
//				startService(intent);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}

	private void initUserHash() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				BusinessModule bModule = getBusinessModule();
				UserHashTaskMark userHashTaskMark = bModule.getTaskMarkPool().getUserHashTaskMark();
				bModule.getServiceWrapper().userHash((IResultReceiver) getApplicationContext(), userHashTaskMark, sharedPrefManager.getUserId(), sharedPrefManager.getAuid());
			}
		}).start();
	}

	private void initAuid() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				DeviceConfig deviceConfig = getDeviceConfig();
				UserGetAuidTaskMark auidTaskMark = getBusinessModule().getTaskMarkPool().createUserGetAuidTaskMark();
				getBusinessModule().getServiceWrapper().userGetAuid((IResultReceiver) getApplicationContext(), auidTaskMark, deviceConfig.getAndroidId(), deviceConfig.getImei());
			}
		}).start();
	}

	private void sendUpdateVersion() {
		BusinessModule bModule = getBusinessModule();
		VersionInfoTaskMark verTaskMark = bModule.getTaskMarkPool().getVersionTaskMark();
		bModule.getServiceWrapper().updateVersion(this, verTaskMark);
	}

	public void registerGcm() {
//		try {
//			BusinessModule bModule = getBusinessModule();
//			UserInfo userInfo = bModule.getCacheManager().getUserInfo();
//			String userId = userInfo == null ? "" : userInfo.getUserID();
//			String regId = bModule.getCacheManager().getRegistrationId();
//			String auid = sharedPrefManager.getAuid();
//			AddUserTokenTaskMark taskMark = bModule.getTaskMarkPool().createAddUserTokenTaskMark();
//			bModule.getServiceWrapper().addUserToken(null, taskMark, userId, regId, "A", auid);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}

	private void sendFcmToken(String token){
		try {
			BusinessModule bModule = getBusinessModule();
			UserInfo userInfo = bModule.getCacheManager().getUserInfo();
			String userId = userInfo == null ? "" : userInfo.getUserID();

			if (StringUtil.isEmptyString(userId)) {
				Log.i(TAG, "is no login");
				return;
			}

			AddUserTokenTaskMark taskMark = bModule.getTaskMarkPool().createAddUserTokenTaskMark();
			bModule.getServiceWrapper().addUserToken(null, taskMark, userId, token);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getModulesConfigName() {
		return "modules.json";
	}

	@Override
	public int getClientMark() {
		return 0;
	}

	@Override
	public int getClientType() {
		return 0;
	}

	@Override
	protected void subHandleMessage(Message msg) {
		switch (msg.what) {
			case PhoConstants.FCM_STATUS_TOKEN:
				String token = msg.obj.toString();
				if (StringUtil.isEmptyString(token)) {
					return;
				}
				//保存regId
				//BusinessModule bModule = getBusinessModule();
				//bModule.getCacheManager().setFcmTokenId(token);
				sendFcmToken(token);

				break;

			case Constants.BUSINESS_STATUS_LOGIN_SUCCESS:
				//initGcm();
				initFcmToken();

				// 获取通知设置
				BusinessModule bModule = getBusinessModule();
				ATaskMark aTaskMark = bModule.getTaskMarkPool().createUserGetNoticationSettingTaskMark();
				UserInfo userInfo = bModule.getCacheManager().getUserInfo();
				String userId = userInfo == null ? "" : userInfo.getUserID();
				if (StringUtil.isEmptyString(userId)) {
					return;
				}
				bModule.getServiceWrapper().userGetNoticationSetting(null, aTaskMark, userId);
				break;

			case Constants.BUSINESS_STATUS_LOGIN_OVERTIME:
				Toast.makeText(this, R.string.login_overtime, Toast.LENGTH_LONG).show();
				clearUserCache();
				break;

			case Constants.BUSINESS_STATUS_SPLASH_AD:
				//请求splash Ad
				BusinessModule bModule1 = getBusinessModule();
				SplashAdInfoTaskMark aTaskMark1 = bModule1.getTaskMarkPool().getSplashAdTaskMark();
				bModule1.getServiceWrapper().sendSplashAd((IResultReceiver) getApplicationContext(), aTaskMark1);
				break;
		}
	}

	public BusinessModule getBusinessModule() {
		return (BusinessModule) getSubModule(PhoConstants.BUSINESS_MODULE);
	}

	@Override
	protected void handleBussnessMessage(Message msg) {

	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		if (taskMark instanceof UserGetAuidTaskMark && taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			AfTrackerUtil.setAppsFlyer(this, sharedPrefManager.getAuid());
			initUserHash();
			//registerGcm();

		} else if (taskMark instanceof VersionInfoTaskMark && taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			initAuid();
			Message msg = new Message();
			msg.what = 1;
			handler.sendMessageDelayed(msg, 3000);
		} else if (taskMark instanceof SplashAdInfoTaskMark && taskMark.getTaskStatus() == ATaskMark.HANDLE_ERROR) {
			SystemEvent.fireEvent(SystemEventConst.EVENT_ACTION_UPDATE_SPLASH_AD);
		}
	}

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			updateVersion();
		}
	};

	private void updateVersion() {
		VersionInfo info = getBusinessModule().getCacheManager().getVersionInfoCache();
		String newVersion = info.getAppVer();
		String currentVersion = AppUtils.getAppVer(MainApplication.this);
		if (AppUtils.isNewVersion(newVersion, currentVersion)) {
			UpdateDialog dialog = new UpdateDialog(getMWindowToken());
			dialog.show();
		}
	}

	public void clearUserCache() {
		clearUserCacheNoGoLogin();

		Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);

	}

	public void clearUserCacheNoGoLogin() {
		getBusinessModule().getCacheManager().setUserInfo(null);

		sharedPrefManager.saveUserId(null);
		sharedPrefManager.saveUserName(null);
		sharedPrefManager.saveUserEmail(null);
		sharedPrefManager.saveAvatar(null);
		sharedPrefManager.saveLogin(null);
		sharedPrefManager.saveTotalUnReadComment(null);
		sharedPrefManager.saveTotalUnReadPostComment(null);
		sharedPrefManager.saveCloseAllMessage(true);
		sharedPrefManager.saveMyArticleNewComment(true);
		sharedPrefManager.saveMyFollowedBusiness(true);
		sharedPrefManager.saveHaveAtCommentMessage(true);

		getBusinessModule().getTaskMarkPool().getFetchEventsTaskMark().reinitTaskMark();
	}

	public synchronized Tracker getTracker(TrackerName appTracker) {
		if (!mTrackers.containsKey(appTracker)) {
			GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
			Tracker t = (appTracker == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
					: (appTracker == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker)
					: analytics.newTracker(R.xml.ecommerce_tracker);
			t.enableAdvertisingIdCollection(true);
			mTrackers.put(appTracker, t);
		}
		return mTrackers.get(appTracker);
	}
}
